using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Decav.Diagnostics;
using Decav.Gatsb.Application;
using System.IO;
using Decav.Gatsb.Configuration;
using Decav.Gatsb.Diagnostics;

namespace Decav.Gatsb.Web
{
    public class ExceptionTrackingHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(Application_Error);
        }

        void Application_Error(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("============EXCEPTION OCCURED============");
            builder.AppendFormat("Date UTC:        {0}\r\n", DateTime.UtcNow);

            try
            {
                builder.AppendFormat("Handler:         {0}\r\n", HttpContext.Current.Request.PhysicalPath);
                builder.AppendFormat("Raw URL:         {0}\r\n", HttpContext.Current.Request.RawUrl);
                builder.AppendFormat("Is Authed:       {0}\r\n", HttpContext.Current.User.Identity.IsAuthenticated);
                builder.AppendFormat("Has User:        {0}\r\n", GatsbApplication.Current.UserPresent);
                if (GatsbApplication.Current.UserPresent)
                {
                    builder.AppendFormat("User ID:         {0}\r\n", GatsbApplication.Current.CurrentUser.Id);
                }
            }
            catch { /* Swallow Exception */ }

            foreach (Exception ex in HttpContext.Current.AllErrors)
            {
                builder.AppendLine("=============EXCEPTION============");
                string str = DecavDiagnostics.GetExceptionDetails(ex);
                builder.AppendLine(str);
                builder.AppendLine("\r\n\r\n\r\n");
            }

            GatsbDiagnostics.WriteLogEntry(builder.ToString(), System.Diagnostics.EventLogEntryType.Error);
        }

        #endregion
    }
}
